/**
 * Copyright (C) 2015 Coderyuan.com. All Rights Reserved.
 *
 * JustLib
 *
 * FlashLightUtil.java created on 2015年6月22日
 *
 * @author yuanguozheng
 * @since 2015年6月22日
 * @version v1.0.0
 */

package com.coderyuan.device;

import android.hardware.Camera;
import android.os.Build;
import android.os.Handler;

@SuppressWarnings("deprecation")
public class FlashLightUtil {

    private static final int OFF_TIME = 3 * 60 * 1000;

    private static Camera sCamera;
    private static Handler sHandler = new Handler();

    public static boolean turnOnFlashLight() {
        if (sCamera == null) {
            sCamera = Camera.open();
            sCamera.startPreview();
            Camera.Parameters parameter = sCamera.getParameters();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
                parameter.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            } else {
                parameter.set("flash-mode", "torch");
            }
            sCamera.setParameters(parameter);
            sHandler.removeCallbacksAndMessages(null);
            sHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    turnOffFlashLight();
                }
            }, OFF_TIME);
        }
        return true;
    }

    public static boolean turnOffFlashLight() {
        if (sCamera != null) {
            sHandler.removeCallbacksAndMessages(null);
            Camera.Parameters parameter = sCamera.getParameters();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
                parameter.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            } else {
                parameter.set("flash-mode", "off");
            }
            sCamera.setParameters(parameter);
            sCamera.stopPreview();
            sCamera.release();
            sCamera = null;
        }
        return true;
    }
}
